#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>

int message = 1;
//pthread_mutex_t mutex = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
//pthread_mutex_init(mutex);
//pthread_mutex_trylock(mutex);
sem_t sem;
void  my_thread_exit(void *arg)
{
    printf("thread name:%s>>> thread is exit!\n", (char *)arg);
}

void *thread1(void *arg)
{
    int fd = *((int *)arg);

    while(1)
    {
        write(fd, "hello", 5);
        write(fd, "world", 5);
        write(fd, "\n", 1);
    }
}

void *thread2(void *arg)
{   
    int fd = *((int *)arg);

    while(1)
    {
        write(fd, "hhhhh", 5);
        write(fd, "wwwww", 5);
        write(fd, "\n", 1);
    }
}

struct Message
{
   int action;
   char msg[100];
};

int main(int argc, char **argv)
{
    int ret;
    pthread_t id1;
    pthread_t id2;
    int num = 5;
    int count = 6;
    char *ptr = "hello world";
    struct Message msg;

    

    int fd = open("a.txt", O_CREAT | O_RDWR | O_TRUNC, 0655);
    if(fd == -1)
    {
        perror("open file error!");
        exit(1);
    }

    ret = pthread_create(&id1, NULL, thread1, (void *)&fd);  //传递地址
    if(ret < 0)
    {
        perror("thread1 create error!");
        exit(1);
    }
    ret = pthread_create(&id2, NULL, thread2, (void *)&fd); //传值
    if(ret < 0)
    {
        perror("thread2 create error!");
        exit(1);
    }
    
    //缺点：阻塞--线程资源不能被立即回收
    pthread_join(id1, NULL); //阻塞等待此线程退出，并且回收资源
    //void *result;
    pthread_join(id2, NULL);
    //printf("result = %s\n", (char *)(result));
    
    //线程：分离态  线程退出系统自动回收线程的资源
    //pthread_detach(id1);
    //pthread_detach(id2);

    printf("id1 = %ld\n", id1);
    printf("id2 = %ld\n", id2);

    printf("num = %d\n", num);

    pause();

    return 0;
}